<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>用户管理 - 表格页面</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="https://www.layuicdn.com/layui/css/layui.css">
</head>
<body>
    
    <!-- 表格页面 -->
    <div class="layui-fluid" style="padding: 15px;">
        <div class="layui-card">
            <div class="layui-card-header">
                <span>用户管理</span>
                <div class="layui-btn-group" style="float: right;">
                    <button class="layui-btn layui-btn-sm" id="addBtn">
                        <i class="layui-icon layui-icon-add-1"></i> 添加
                    </button>
                </div>
            </div>
            <div class="layui-card-body">
                <table class="layui-hide" id="userTable" lay-filter="userTable"></table>
            </div>
        </div>
    </div>

    <!-- 表格操作栏模板 -->
    <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-xs" lay-event="edit">修改</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>

    <!-- 隐藏的表单内容 -->
    <div id="userFormContent" style="display: none; padding: 20px;">
        <form class="layui-form" lay-filter="userFormFilter" id="userForm">
            <input type="hidden" name="id" id="userId">
            
            <div class="layui-form-item">
                <label class="layui-form-label">姓名</label>
                <div class="layui-input-block">
                    <input type="text" name="name" id="userName" placeholder="请输入姓名" class="layui-input" lay-verify="required">
                </div>
            </div>
            
            <div class="layui-form-item">
                <label class="layui-form-label">年龄</label>
                <div class="layui-input-block">
                    <input type="number" name="age" id="userAge" placeholder="请输入年龄" class="layui-input" lay-verify="required|number">
                </div>
            </div>
            
            <div class="layui-form-item">
                <label class="layui-form-label">邮箱</label>
                <div class="layui-input-block">
                    <input type="email" name="email" id="userEmail" placeholder="请输入邮箱" class="layui-input" lay-verify="required|email">
                </div>
            </div>
            
            <div class="layui-form-item">
                <label class="layui-form-label">性别</label>
                <div class="layui-input-block">
                    <input type="radio" name="gender" value="男" title="男">
                    <input type="radio" name="gender" value="女" title="女">
                </div>
            </div>
            
            <div class="layui-form-item">
                <label class="layui-form-label">状态</label>
                <div class="layui-input-block">
                    <select name="status" id="userStatus" lay-verify="required">
                        <option value="">请选择状态</option>
                        <option value="启用">启用</option>
                        <option value="禁用">禁用</option>
                    </select>
                </div>
            </div>
            
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button type="submit" class="layui-btn" lay-submit lay-filter="submitBtn">提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary" id="resetBtn">重置</button>
                    <button type="button" class="layui-btn layui-btn-primary" id="cancelBtn">取消</button>
                </div>
            </div>
        </form>
    </div>

    <script src="https://www.layuicdn.com/layui/layui.js"></script>
    <script>
    layui.use(['table', 'layer', 'form'], function(){
        var table = layui.table,
            layer = layui.layer,
            form = layui.form,
            $ = layui.$;

        // 模拟数据存储
        var userData = [
            {id: 1, name: '张三', age: 25, email: 'zhangsan@example.com', gender: '男', status: '启用'},
            {id: 2, name: '李四', age: 30, email: 'lisi@example.com', gender: '女', status: '启用'},
            {id: 3, name: '王五', age: 28, email: 'wangwu@example.com', gender: '男', status: '禁用'}
        ];

        // 当前操作状态
        var currentAction = '';
        var currentEditId = null;

        // 渲染表格
        var tableIns = table.render({
            elem: '#userTable',
            data: userData,
            cols: [[ 
                {field: 'id', title: 'ID', width: 80, sort: true},
                {field: 'name', title: '姓名', width: 120},
                {field: 'age', title: '年龄', width: 80},
                {field: 'email', title: '邮箱', width: 200},
                {field: 'gender', title: '性别', width: 80},
                {field: 'status', title: '状态', width: 100},
                {title: '操作', toolbar: '#barDemo', width: 150, align: 'center'}
            ]],
            page: false,
            height: 'full-220'
        });

        // 刷新表格数据
        function refreshTable() {
            tableIns.reload({
                data: userData
            });
        }

        // 清空表单
        function clearForm() {
            $('#userId').val('');
            $('#userName').val('');
            $('#userAge').val('');
            $('#userEmail').val('');
            $('#userStatus').val('');
            // 清空单选框选中状态
            $('input[name="gender"]').prop('checked', false);
        }

        // 填充表单数据
        function fillForm(data) {
            $('#userId').val(data.id);
            $('#userName').val(data.name);
            $('#userAge').val(data.age);
            $('#userEmail').val(data.email);
            $('#userStatus').val(data.status);
            
            // 设置单选框
            $('input[name="gender"][value="' + data.gender + '"]').prop('checked', true);
            
            // 重新渲染表单以更新UI
            form.render();
        }

        // 添加按钮点击事件
        $('#addBtn').on('click', function(){
            currentAction = 'add';
            currentEditId = null;
            openUserForm('添加用户');
        });

        // 表格工具栏事件
        table.on('tool(userTable)', function(obj){
            var data = obj.data;
            if(obj.event === 'del'){
                layer.confirm('确定删除这条记录吗?', function(index){
                    // 删除数据
                    for(var i = 0; i < userData.length; i++){
                        if(userData[i].id === data.id){
                            userData.splice(i, 1);
                            break;
                        }
                    }
                    refreshTable();
                    layer.close(index);
                    layer.msg('删除成功', {icon: 1});
                });
            } else if(obj.event === 'edit'){
                currentAction = 'edit';
                currentEditId = data.id;
                openUserForm('修改用户', data);
            }
        });

        // 打开用户表单
        function openUserForm(title, data) {
            layer.open({
                type: 1,
                title: title,
                content: $('#userFormContent'),
                area: ['500px', '600px'],
                success: function(){
                    // 先清空表单
                    clearForm();
                    
                    if(currentAction === 'edit' && data) {
                        // 编辑模式，填充数据
                        setTimeout(function() {
                            fillForm(data);
                        }, 100); // 延时一点确保DOM准备好
                    } else {
                        // 添加模式，设置默认值
                        setTimeout(function() {
                            $('input[name="gender"][value="男"]').prop('checked', true);
                            form.render();
                        }, 100);
                    }
                }
            });
        }

        // 表单提交事件
        form.on('submit(submitBtn)', function(data){
            var formData = data.field;
            
            // 转换数据类型
            if(formData.age) {
                formData.age = parseInt(formData.age);
            }
            
            // 验证必填字段
            if(!formData.name || !formData.age || !formData.email || !formData.gender || !formData.status) {
                layer.msg('请填写完整信息', {icon: 2});
                return false;
            }
            
            if(currentAction === 'edit' && currentEditId) {
                // 修改操作
                formData.id = parseInt(currentEditId);
                for(var i = 0; i < userData.length; i++){
                    if(userData[i].id === formData.id){
                        userData[i] = formData;
                        break;
                    }
                }
                layer.msg('修改成功', {icon: 1});
            } else {
                // 添加操作
                var maxId = 0;
                if(userData.length > 0){
                    maxId = Math.max.apply(Math, userData.map(function(item){
                        return item.id;
                    }));
                }
                formData.id = maxId + 1;
                userData.push(formData);
                layer.msg('添加成功', {icon: 1});
            }
            
            // 刷新表格
            refreshTable();
            
            // 关闭弹层
            layer.closeAll();
            
            return false;
        });

        // 重置按钮事件
        $(document).on('click', '#resetBtn', function(){
            if(currentAction === 'edit') {
                // 编辑模式下重置为原始数据
                var originalData = null;
                for(var i = 0; i < userData.length; i++){
                    if(userData[i].id === currentEditId){
                        originalData = userData[i];
                        break;
                    }
                }
                if(originalData) {
                    fillForm(originalData);
                }
            } else {
                // 添加模式下清空表单
                clearForm();
                $('input[name="gender"][value="男"]').prop('checked', true);
                form.render();
            }
        });

        // 取消按钮事件
        $(document).on('click', '#cancelBtn', function(){
            layer.closeAll();
        });
    });
    </script>
</body>
</html>